<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<%@ page import="com.party.core.model.system.TargetType" %>

<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${epCategory.id == null ?'发布' : '编辑'}服务</title>
    <%@include file="../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/common/img_text.css">
    <link rel="stylesheet" href="${ctx}/static/uploadCI/upload.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <link rel="stylesheet" href="${ctx}/css/ui/mall/goods_form.css">
    <link rel="stylesheet" href="${ctx}/css/form-preview.css">
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">

            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/epService/epService/save.do">
                    <input type="hidden" name="id" value="${epService.id}"/>
                    <div class="layui-form-item">
                        <label class="layui-form-label">服务名称<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="服务名称"
                                   class="layui-input" value="${epService.title}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">封面图<span class="f-verify-red">*</span></label>
                        <div class="cover-content">
                            <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${epService.pic}"/>
                            <c:if test="${epService == null || empty epService.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url(${ctx}/image/posterImg.png)"></span>
                            </c:if>
                            <c:if test="${epService != null && not empty epService.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url('${epService.pic}')"></span>
                            </c:if>
                            <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加封面图</a>
                            <div class="form-word-aux">建议尺寸：800x450</div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">服务简介<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="subTitle" lay-verify="subTitle" autocomplete="off" placeholder="服务简介" class="layui-input"
                                   value="${epService.subTitle}">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">服务分类<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="hidden" name="categoryList" id="categoryIds" value=""
                                   lay-verify="categoryList"/>
                            <div class="tag-wrap">
                                <c:forEach var="category" items="${categoryList}">
                                    <div class="tag-item" data-id="${category.id}">
                                        <span class="tag-name">${category.name}</span>
                                        <i class="iconfont icon-close category-opt"></i>
                                    </div>
                                </c:forEach>
                            </div>
                            <a href="javascript:selectCategory();" class="layui-btn layui-btn-danger addCategoryBtn"
                               style="float: left; margin-right: 10px;">
                                <i class="iconfont icon-add btn-icon"></i>
                                选择分类
                            </a>
                            <div class="layui-form-mid layui-word-aux"><a href="${ctx}/epService/category/list.do" class="red">新增分类</a>
                            </div>
                            <i class="cl"></i>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">排序<span class="f-verify-red">*</span></label>
                            <div class="layui-input-inline">
                                <input type="number" name="sort" lay-verify="sort" autocomplete="off" class="layui-input"
                                       value="${epService.sort}">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item"
                         id="localDiv">
                        <label class="layui-form-label">服务详情<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <script id="ueditor1" type="text/plain"></script>
                            <div style="display: none" id="contentView">${epService.content}</div>
                            <input type="hidden" name="content" id="content" lay-verify="content"/>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <a href="${ctx}/epService/epService/list.do"
                               class="layui-btn layui-btn-primary">取消</a>
                        </div>
                    </div>
                </form>
            </div>
        </div><!--底部-->
        <%@include file="../include/footer.jsp" %>
    </section>
</div>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script>
    txz.initHeader({
        nav: [{
            name: '服务管理',
            href: '${ctx}/epService/epService/list.do'
        }, {
            name: '${epCategory == null ? '发布' : '编辑'}服务',
            curr: true
        }],
        btns: [{
            name: '返回',
            href: 'javascript:history.back();',
            icon: 'back'
        }]
    });

    var ue = UE.getEditor('ueditor1', {
        initialFrameHeight: 500,//设置编辑器高度
        scaleEnabled: true
    });


    $(function () {
        layui.use(['form'], function () {
            var form = layui.form, laydate = layui.laydate;
            var formcache;

            var typeRadioValue = null;

            form.on('radio(isShow)', function (data) {
                if (data.value == "1") {
                    $('[data-showApply=1]').show();
                } else {
                    $('[data-showApply=1]').hide();
                }
            });

            form.on('radio(type)', function (data) {
                typeRadioValue = data.value;
                if (typeRadioValue == "out") {
                    $("#urlDiv").show();
                    $("#localDiv").hide();
                } else if (typeRadioValue == "local") {
                    $("#urlDiv").hide();
                    $("#localDiv").show();
                }
            });

            //自定义验证规则
            form.verify({
                title: function (value) {
                    if (value == "") {
                        return '请填写服务名称';
                    }
                    if (value.length>50) {
                        return '名称长度不能大于50';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传封面图";
                    }
                },
                subTitle: function (value) {
                    if (value == "") {
                        return "简介不能为空";
                    }
                    if (value.length>100) {
                        return "简介长度不能大于100";
                    }
                },
                categoryList: function (value) {

                    var length = $(".tag-item").length;
                    if (length == 0) {
                        return "请选择分类";
                    }
                },
                sort: function (value) {
                    if (value == "") {
                        return "序号不能为空";
                    }
                    if (value <= 0) {
                        return "请输入正确的序号";
                    }
                },
                content: function (value) {

                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (content == "") {
                        return "请输入服务详情";
                    }
                }
            });
            form.render(); //更新全部

            //监听提交
            form.on('submit', function (data) {
                submitForm(data);
                localStorage.removeItem("server_epCategory");
            });



            $(".tag-wrap").delegate(".category-opt", "click", function (e) {
                var target = $(e.target);
                var value = $(target).closest(".tag-item").data("id");
                $(target).closest(".tag-item").remove();

                var giftJson = localStorage.getItem("server_epCategory");
                var _giftArray = eval(giftJson);

                var index = -1; // 如果不存在返回-1，否则返回index
                $.each(_giftArray, function (ii, dd) {
                    if (value == dd.id) {
                        index = ii;
                    }
                });
                _giftArray.splice(index, 1);
                localStorage.setItem("server_epCategory", JSON.stringify(_giftArray));
            })


            function getFormData() {

                // 分类
                var _giftArray = new Array();
                var _categoryArray = new Array();
                $(".tag-wrap .tag-item").each(function (index, elem) {
                    var tagId = $(elem).data("id");
                    var tagName = $(elem).find(".tag-name").text();
                    _giftArray.push(tagId);
                    var map = {
                        id: tagId,
                        name: tagName
                    };
                    _categoryArray.push(map);
                });
                if (_giftArray.length > 0) {
                    $("#categoryIds").val(_giftArray.join(","));
                    $("[name=categoryCache]").val(JSON.stringify(_categoryArray));
                }
                $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
                return util.serializeForm($('#myForm').serializeArray());
            }

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
                    var formData = getFormData();
                    var action = $("#myForm").attr("action");
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    location.href = "${ctx}/epService/epService/list.do"
                                });
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    });
                })
            }

        });
        ue.addListener('ready', function () {
            this.setContent($("#contentView").html());
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });
        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.ARTICLE.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
    })

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }


    function selectCategory() {
        function cb($jquery) {
            var categoryIds = $($jquery.find("#categoryIds")).val();
            var categoryNames = $($jquery.find("#categoryNames")).val();
            var _idsArray = categoryIds.split(",");
            var _namesArray = categoryNames.split(",");
            var _contentArray = new Array();
            for (var i = 0; i < _idsArray.length; i++) {
                _contentArray.push('<div class="tag-item" data-id="' + _idsArray[i] + '">');
                _contentArray.push('<span class="tag-name">' + _namesArray[i] + '</span>');
                _contentArray.push('<i class="iconfont icon-close category-opt"></i>');
                _contentArray.push('</div>');
            }
            var $content = $(".tag-wrap");
            $content.html(_contentArray.join(""));

        }
        var _giftArray = new Array();
        $(".tag-wrap .tag-item").each(function (index, elem) {
            var giftId = $(elem).data("id");
            _giftArray.push(giftId);
        });
        var categoryIds = _giftArray.join(",");

        openDialog('选择分类', '${ctx}/epService/category/selectEpCategoryList.do?categoryIds=' + categoryIds, '450px', '600px', cb);
    }

    function openDialog(title, url, width, height, cb, target) {
        layer.open({
            type: 2,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url,
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                var inputForm = body.find('#inputForm');
                var top_iframe;
                if (target) {
                    top_iframe = target;//如果指定了iframe，则在改frame中跳转
                } else {
                    top_iframe = '_parent';//获取当前active的tab的iframe
                }
                inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                if (iframeWin.contentWindow.doSubmit()) {
                    cb(iframeWin.contentWindow.$);

                    setTimeout(function () {
                        top.layer.close(index);
                    }, 100);//延时0.1秒，对应360 7.1版本bug
                }

            },
            cancel: function (index) {
            }
        });
    }

</script>
</body>
</html>